#include "stdafx.h"
#include "contour.h"

void contour_initial(countour_t * pct)
{
	pct->base.add_fun = contour_ptctn_add_fun;
	pct->ctps = 0;
	pct->count = 0;
	pct->length = 0;
	pct->outter_join = line_join_bevel;
	pct->miter_limit = 10.0f;
	pct->miter_max = 0.0f;

	pct->off_x = 0;
	pct->off_y = 0;

	pct->min_x = pct->min_y = F32_MAX;
	pct->max_x = pct->max_y = F32_MIN;
}

void contour_reset(countour_t * pct)
{
	pct->count = 0;
	pct->miter_max = 0.0f;
	pct->min_x = pct->min_y = F32_MAX;
	pct->max_x = pct->max_y = F32_MIN;
}

void contour_destroy(countour_t * pct)
{
	drawing_free(pct->ctps);
}

int_32 contour_add(countour_t * pct, float_32 x, float_32 y, command_e cmd)
{
	drawing_assert(!drawing_isnan(x));
	drawing_assert(!drawing_isnan(y));

	x += pct->off_x;
	y += pct->off_y;

	if(pct->count == pct->length)
	{
		int_32 count = pct->length + 256;
		countour_point_t * ctps = (countour_point_t *)drawing_malloc(count * sizeof(countour_point_t));
		drawing_memset(ctps, 0, count * sizeof(countour_point_t));
		drawing_memcpy(ctps, count * sizeof(countour_point_t), pct->ctps, pct->length * sizeof(countour_point_t));
		drawing_free(pct->ctps);
		pct->ctps = ctps;
		pct->length = count;
	}

	countour_point_t * ctp = pct->ctps + pct->count;
	ctp->x = x;
	ctp->y = y;
	ctp->cmd = cmd;

	if(cmd == command_move)
	{
		pct->start_x = x - pct->off_x;
		pct->start_y = y - pct->off_y;
	}


	if(x < pct->min_x)
		pct->min_x = x;
	/*else*/ if(x > pct->max_x)
		pct->max_x = x;
	//else {}

	if(y < pct->min_y)
		pct->min_y = y;
	/*else*/ if(y > pct->max_y)
		pct->max_y = y;
	//else {}

	return (pct->count)++;
}

int_32 contour_ptctn_add_fun(tag_point_container * ptctn, float_32 x, float_32 y, command_e cmd)
{
	switch(cmd)
	{
	case command_close_last:
		{
			countour_t * ct = (countour_t *)ptctn;
			if(ct->count < 2)
				break;
			countour_point_t * ctpt = ct->ctps + ct->count - 1;
			ctpt->cmd = command_close;
		}
		break;
	default:
		return contour_add((countour_t *)ptctn, x, y, cmd);
		break;
	}
	return -1;
}